<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User\WeightModel;
use Carbon\Carbon;
use Illuminate\Http\Request;

class WeightManagementController extends Controller
{
    public function list(Request $request)
    {
        $list = WeightModel::query()
            ->where('user_id', $request->user_id)
            ->orderByDesc('id')
            ->limit(30)
            ->get();

        return $this->success(collect($list)->sortBy('id')->values());
    }


    public function setInfo(Request $request)
    {
        $height                   = $request->post('height');
        $targetWeight             = $request->post('targetWeight');
        $userModel                = $request->user();
        $userModel->height        = $height;
        $userModel->target_weight = $targetWeight;
        $userModel->save();

        return $this->success();
    }

    public function add(Request $request)
    {
        $weight = $request->post('weight');
        $date   = $request->post('date', '');

        // 判断用户今日是否添加

        if (mb_strlen($date) == 0) {
            $time = Carbon::now();
        } else {
            $time = Carbon::createFromDate($date);
        }

        $todayWeightRecord = WeightModel::query()
            ->where('user_id', $request->user_id)
            ->whereBetween('created_at', [$time->startOfDay()->timestamp, $time->endOfDay()->timestamp])
            ->first();

        if ($todayWeightRecord) {
            // 已经设置 进行调整

            // 计算前7天的均值
            $weightRecordAverageRecord = WeightModel::query()
                ->where('user_id', $request->user_id)
                ->orderByDesc('id')
                ->limit(7)
                ->get();

            $average                              = ($weightRecordAverageRecord->sum('weight') - $todayWeightRecord->weight + $weight) / $weightRecordAverageRecord->count();
            $todayWeightRecord->weight            = $weight;
            $todayWeightRecord->seven_day_average = number_format($average, 2, '.', '');
            $todayWeightRecord->created_at        = $time->timestamp;
            $todayWeightRecord->updated_at        = $time->timestamp;
            $todayWeightRecord->save();
        } else {
            // 未设置
            // 计算前6天的均值
            $weightRecordAverageRecord = WeightModel::query()
                ->where('user_id', $request->user_id)
                ->orderByDesc('id')
                ->limit(6)
                ->get();

            $average = ($weightRecordAverageRecord->sum('weight') + $weight) / ($weightRecordAverageRecord->count() + 1);

            $weightRecord                    = new WeightModel();
            $weightRecord->user_id           = $request->user_id;
            $weightRecord->weight            = $weight;
            $weightRecord->seven_day_average = number_format($average, 2, '.', '');
            $weightRecord->created_at        = $time->timestamp;
            $weightRecord->updated_at        = $time->timestamp;
            $weightRecord->save();
        }

        return $this->success();
    }


    public function stats(Request $request)
    {
        $currentWeight   = 0;
        $yesterdayWeight = 0;
        WeightModel::query()
            ->where('user_id', $request->user_id)
            ->orderByDesc('id')
            ->limit(2)
            ->get()
            ->map(function ($item) use (&$currentWeight, &$yesterdayWeight) {
                if ($currentWeight == 0) {
                    $currentWeight = $item->weight;
                }
                $yesterdayWeight += $item->weight;
            });

        if (!$request->user()->target_weight || !$request->user()->height) {
            return $this->error('请先设置身高与理想体重');
        }

        return $this->success([
            "current_weight" => $currentWeight,
            "bmi"            => $this->bmi($currentWeight, $request->user()->height),
            "target_weight"  => $request->user()->target_weight,
            "weight_diff"    => $currentWeight - $yesterdayWeight,
            "height"         => $request->user()->height,
        ]);
    }


    public function bmi($weight, $height)
    {
        // 计算BMI：体重(kg) / (身高(m)的平方)
        $heightM = $height / 100; // 将cm转换为m
        $bmi     = round($weight / ($heightM * $heightM), 2);

        // BMI分类
        $category = $this->getBmiCategory($bmi);

        return [
            'bmi'                 => $bmi,
            'category'            => $category,
            'standard_weight_min' => round(18.5 * $heightM * $heightM, 2),
            'standard_weight_max' => round(23.9 * $heightM * $heightM, 2),
        ];
    }

    /**
     * 获取BMI分类
     */
    private function getBmiCategory(float $bmi): string
    {
        if ($bmi < 18.5) {
            return '偏瘦';
        } elseif ($bmi < 24) {
            return '正常';
        } elseif ($bmi < 28) {
            return '超重';
        } else {
            return '肥胖';
        }
    }


}
